//
//  Find_ContentView.m
//  SoundPill
//
//  Created by 宋旭东 on 15/6/10.
//  Copyright (c) 2015年 宋旭东. All rights reserved.
//

#import "Find_ContentView.h"
#import "Find_Content_Model.h"
#import "Find_ContentCreateTopicView.h"
#import "AppDelegate.h"
#import "UIViewExt.h"
#import "JCAlertView.h"
#import "Pictures.h"
#import "AppDelegate.h"
#import "UIImageView+WebCache.h"

#define Screen_width  [[UIScreen mainScreen] bounds].size.width
#define Screen_height [[UIScreen mainScreen] bounds].size.height
@interface Find_ContentView ()<UITableViewDelegate,UITableViewDataSource,MJRefreshBaseViewDelegate>
{
    int page;
    int lastPage;
    int pages;
    NSString *_filePath;
    MJRefreshFooterView *fotter;
}
@property (nonatomic, strong) Find_ContentCreateTopicView *topicCreateView;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) NSMutableArray *pictureArray;
@property (nonatomic, strong) UIPageControl *pageControl;
@property (nonatomic, strong) NSTimer *timer;
@property (strong, nonatomic) AMPopTip *popTip;
@end

@implementation Find_ContentView
- (instancetype)initWithFrame:(CGRect)frame popTip:(AMPopTip *)popTip
{
    self = [super initWithFrame:frame];
    if (self) {
        _contentArray = [NSMutableArray array];
        [self createTableView];
        NSString * cachPath = [ NSSearchPathForDirectoriesInDomains ( NSCachesDirectory , NSUserDomainMask , YES ) firstObject ];
        _filePath = [cachPath stringByAppendingPathComponent:@"find_content"];
        if ([[NSFileManager defaultManager] fileExistsAtPath:_filePath]) {
            NSData *data = [NSData dataWithContentsOfFile:_filePath];
            NSDictionary *content = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            [self reloadContentData:content pag:1];
            page = 1;
        } else {
            [self.header beginRefreshing];
        }
        self.popTip = popTip;
    }
    return self;
}
#pragma mark -
- (void)hideFooterView
{
//    if(_ContentTableView.contentSize.height >= self.frame.size.height ){
//        _personTableView.tableFooterView.hidden=NO;
        fotter.hidden = YES;
        //footLabel.hidden = NO;
//    }else{
//        fotter.hidden = NO;
//    }
}

#pragma mark -
#pragma mark 创建列表
- (void)createTableView
{
    self.ContentTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    _ContentTableView.delegate = self;
    _ContentTableView.dataSource = self;
    _ContentTableView.showsVerticalScrollIndicator = NO;
    _ContentTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    _ContentTableView.separatorColor = [UIColor colorWithRed:0.895 green:0.898 blue:0.908 alpha:1.000];
    _ContentTableView.separatorInset = UIEdgeInsetsZero;
//    [_ContentTableView setTableHeaderView:_scrollView];
    [self addSubview:_ContentTableView];
    UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, 40)];
    headerLabel.userInteractionEnabled = YES;
    headerLabel.textAlignment = NSTextAlignmentCenter;
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"没有找到感兴趣的话题？你可以 创建话题"];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(0,14)];
    [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14] range:NSMakeRange(0, 14)];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(14, 5)];
    [str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:14] range:NSMakeRange(14, 5)];
    headerLabel.attributedText = str;
    UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tableviewHeaderTap)];
    [headerLabel addGestureRecognizer:recognizer];
    _ContentTableView.tableHeaderView = headerLabel;
    UIView *headerline = [[UIView alloc] initWithFrame:CGRectMake(0, 40, headerLabel.frame.size.width, 0.5)];
    headerline.backgroundColor = [UIColor colorWithRed:0.895 green:0.898 blue:0.908 alpha:1.000];
    [headerLabel addSubview:headerline];
    
    if ([self.ContentTableView respondsToSelector:@selector(setSeparatorInset:)])
    {
        [self.ContentTableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([self.ContentTableView respondsToSelector:@selector(setLayoutMargins:)])
    {
        [self.ContentTableView setLayoutMargins:UIEdgeInsetsZero];
    }
    //刷新控件
    self.header = [MJRefreshHeaderView header];
    _header.scrollView = _ContentTableView;
    _header.delegate = self;

    fotter = [MJRefreshFooterView footer];
    fotter.scrollView = _ContentTableView;
    fotter.delegate = self;
}
- (void)tableviewHeaderTap
{
    if ([[NSUserDefaults standardUserDefaults] valueForKey:@"uid"] != nil) {
        self.topicCreateView = [[Find_ContentCreateTopicView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, [UIScreen mainScreen].bounds.size.height)];
        //    if ([UIScreen mainScreen].bounds.size.height > 667) {
        //        _topicCreateView.frame = CGRectMake(20, 60, self.frame.size.width - 40, 400);
        //    }
        _topicCreateView.backgroundColor = [UIColor clearColor];
        [[AppDelegate shareDelegate].window addSubview:_topicCreateView];
        
        [UIView animateWithDuration:0.4 animations:^{
            _topicCreateView.backgroundColor = [UIColor colorWithWhite:0.000 alpha:0.700];
        } completion:^(BOOL finished) {
            
        }];
        __weak Find_ContentCreateTopicView *view = _topicCreateView;
        _topicCreateView.block = ^(){
            [view removeFromSuperview];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"findToRecordWithTopic" object:nil];
        };
        _topicCreateView.cancel = ^(){
            [view removeFromSuperview];
        };
    } else {
        [JCAlertView showTwoButtonsWithTitle:@"未登录" Message:@"登录后才能继续操作" ButtonType:JCAlertViewButtonTypeCancel ButtonTitle:@"再看看" Click:^{
            
        } ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"去登录" Click:^{
            [[AppDelegate shareDelegate] chooseRootViewController];
        }];

    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _contentArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_contentArray.count == 0) {
        return 0;
    }
    Find_Content_Model *model = _contentArray[indexPath.row];
    if (model.topicDetail.length > 0) {
        CGFloat height = [UIScreen mainScreen].bounds.size.height * 0.30971 + 20;
        return height;
    } else {
        CGFloat height = [UIScreen mainScreen].bounds.size.height * 0.30971;
        return height;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ContentTableIdentifer = @"content";
    _contentCell = [tableView dequeueReusableCellWithIdentifier:ContentTableIdentifer];
    if (_contentCell == nil) {
        _contentCell = [[Find_ContentTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ContentTableIdentifer];
        _contentCell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    if (_contentArray.count > 0) {
        [_contentCell removeSubviews];
        [_contentCell createSubviews:_contentArray[indexPath.row]];
        _contentCell.popTip = self.popTip;
    }
//    contentCell.reason.text = [NSString stringWithFormat:@"%d", indexPath.row];
    return _contentCell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.popTip isVisible]) {
        
        [[NSNotificationCenter defaultCenter]postNotificationName:@"hidePopview" object:nil];
    }
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)])
    {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)])
    {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    BOOL isHeader = [refreshView isKindOfClass:[MJRefreshHeaderView class]];
    if (isHeader) {
        page = 1; // 第一页
        fotter.hidden = NO;
        [_contentArray removeAllObjects];
        [self AFNetworking:page refreshing:refreshView];
    }else { // 上拉加载更多
        if (pages == 1 || page == pages) {
            [self hideFooterView];
        } else {
            page++;
            [self AFNetworking:page refreshing:refreshView];
        }
    }
}
- (void)refreshViewEndRefreshing:(MJRefreshBaseView *)refreshView
{

}
- (void)AFNetworking:(int)pag refreshing:(MJRefreshBaseView *)refreshView
{
    NSString *url = [NSString stringWithFormat:@"http://123.57.1.143/api/tag/discover?p=%d&type=%ld", pag,_type];
    NSString *requestheader = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setValue:requestheader forHTTPHeaderField:@"authorization"];
    [manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [self reloadContentData:responseObject pag:pag];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [refreshView endRefreshing];
        });
        if (pag == 1) {
            //            BOOL result =
//            [operation.responseData writeToFile:_filePath atomically:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [refreshView endRefreshing];
    }];
}
- (void)reloadContentData:(id)responseObject pag:(int)pag
{
    NSDictionary *bigDic = responseObject;
    NSDictionary *dic = [bigDic valueForKey:@"data"];
    for (NSDictionary *dict in dic) {
        Find_Content_Model *model = [[Find_Content_Model alloc] init];
        [model setValuesForKeysWithDictionary:dict];
        [_contentArray addObject:model];
    }
    NSDictionary *meta = [bigDic valueForKey:@"meta"];
    if (meta != nil) {
        pages = [[meta valueForKey:@"pages"] intValue];
        if (pages == 1 || pag == pages) {
            [self hideFooterView];
        }
    }
    [_ContentTableView reloadData];
    _ContentTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
}
//- (UITableViewCell *)tableView:(UITableView *)tableView
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
